package com.xin.lv.yang.utils.utils;

import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.DiskCache;
import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.AppGlideModule;
import java.io.File;

@com.bumptech.glide.annotation.GlideModule
public class GlideConfiguration extends AppGlideModule {

    private static final int DISK_CACHE_SIZE = 100 * 1024 * 1024;
    private static final int MAX_MEMORY_CACHE_SIZE = 10 * 1024 * 1024;


    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {

        // 设置磁盘缓存的路径 path
        final File cacheDir = new File(FileUtils.getCachePath(context, "glide"));

        builder.setDiskCache(new DiskCache.Factory() {
            @Override
            public DiskCache build() {
                return DiskLruCacheWrapper.get(cacheDir, DISK_CACHE_SIZE);
            }
        });

        //设置内存缓存大小，一般默认使用glide内部的默认值
        builder.setMemoryCache(new LruResourceCache(MAX_MEMORY_CACHE_SIZE));


        MemorySizeCalculator.Builder bbb = new MemorySizeCalculator.Builder(context);
        MemorySizeCalculator calculator = bbb.build();

        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

        int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
        int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

        builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
        builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));

    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {

    }
}
